package de.isibboi.cassandraintro;

import java.util.ArrayList;
import java.util.List;

import me.prettyprint.cassandra.serializers.StringSerializer;
import me.prettyprint.cassandra.service.template.ColumnFamilyResult;
import me.prettyprint.cassandra.service.template.ColumnFamilyTemplate;
import me.prettyprint.cassandra.service.template.ThriftColumnFamilyTemplate;
import me.prettyprint.hector.api.Keyspace;
import me.prettyprint.hector.api.exceptions.HectorException;

/**
 * A program that lists all string key-value pairs from Cassandra.
 * 
 * @author Sebastian Schmidt
 */
public class CassandraReader {
	/**
	 * Starts the program.
	 * 
	 * @param args
	 *            Program arguments.
	 */
	public static void main(String[] args) {
		Keyspace keyspace = CassandraUtil.getKeyspace(CassandraUtil.KEYSPACE, CassandraUtil.COLUMN_FAMILY);

		ColumnFamilyTemplate<String, String> template = new ThriftColumnFamilyTemplate<String, String>(keyspace,
				CassandraUtil.COLUMN_FAMILY, StringSerializer.get(), StringSerializer.get());

		List<String> keys = new ArrayList<>(args.length);

		for (String arg : args) {
			keys.add(arg);
		}

		try {
			ColumnFamilyResult<String, String> result = template.queryColumns(keys);
			System.out.println(result.getKey() + " => " + result.getString("value"));

			while (result.hasNext()) {
				result = result.next();
				System.out.println(result.getKey() + " => " + result.getString("value"));
			}
		} catch (HectorException e) {
			printUsageAndExit("An error occurred during reading: " + e.getMessage());
		}
	}

	/**
	 * Prints some usage information and exits the program. This method never
	 * returns.
	 * 
	 * @param error
	 *            An error message to print.
	 */
	private static void printUsageAndExit(String error) {
		System.out.println("Error: " + error);
		System.out.println("Format: java -jar <yourjarname.jar> <name> [<name> ...]");

		System.exit(-1);
	}
}